package com.lagou.edu.utils;

import java.util.Date;

public class FixedWindow {
    public static void main(String[] args) {
        FixedWindow fixedWindow = new FixedWindow();
        do { }while (fixedWindow.trafficMonitoring());
        System.out.println(fixedWindow.getCount());
    }
    private long time = new Date().getTime();
    private Integer count = 0; // 计数器
    private final Integer max = 100; // 请求阈值
    private final Integer interval = 1000; // 窗口大小(固定窗格)
    public boolean trafficMonitoring() {
        long nowTime = new Date().getTime();
        if (nowTime < time + interval) {
            // 在时间窗口内
            count++;
            return max > count;
        } else {
            time = nowTime; // 开启新的窗口
            count = 1; // 初始化计数器,由于这个请求属于当前新开的窗口，所以记录这个请求
            return true;
        }
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }
}